/*
 * @Author: wukunling 13022195532@163.com
 * @Date: 2024-11-01 11:25:24
 * @LastEditors: wukunling 13022195532@163.com
 * @LastEditTime: 2024-11-19 14:09:59
 * @FilePath: /discount/file-server/index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const express = require('express');
const Minio = require('minio');
const fs = require('minio');
const bodyParser = require('body-parser'); // 解析 req.body
const multer = require('multer');//formdata数据处理
const cors = require('cors'); //设置允许跨域
const upload = multer();

const minioClient = new Minio.Client({
    endPoint: '47.121.182.221',
    port: 9014,
    useSSL: false,
    accessKey: '7yqcLZWCPIRzUlKtB4kL', //这里换成自己的
    secretKey: 'ZP2tJFH7zH7o8AwOtJHOPGwwNABi5Rx7P2jrVESR', //这里换成自己的
});

const app = express();
app.use(cors());
app.use(bodyParser.json());

app.post('/upload', upload.single('file'), async (req, res) => {
  try {
    const file = req.file; // 获取上传文件
    const bucketName = 'public'; //自己创建的桶名
    const objectName =new Date().getTime() +'_'+file.originalname; // 设置对象名称
    const stream = Buffer.from(req.file.buffer, 'binary');
    const data = await minioClient.putObject(bucketName, objectName, stream); // 上传到MinIO
    console.log(data);
    res.send({
      code: 200,
      name:objectName,
      bucketName,
      url: `/${bucketName}/${objectName}`, // 返回访问URL
    });
  } catch (err) {
    res.status(500).send(err);
  }
});

app.listen(9013, () => {
  console.log('listening on port 9013');
  console.log('文件服务 9013');
});

